# 添加键值对
def dict_add():
    my_dict = {'name': 'cendy', 'age': 18}
    my_dict['sex'] = '女'
    print(my_dict)
    my_dict['name'] = 'bob'
    print(my_dict)
    print('---------添加结束！---------------')


# 修改键值对
def dict_update():
    my_dict = {'name': 'cendy', 'age': 18}
    my_dict['age'] = 22
    print(my_dict)
    print('---------修改结束！---------------')


# 删除键值对
def dict_delete():
    try:
        my_dict = {'name': 'cendy', 'age': 18, 'sex': '女', 'address': '上海'}
        print('my_dict：', my_dict)
        del my_dict['sex']
        print('my_dict(删除sex)：', my_dict)
        # del my_dict['phone']
        # print('my_dict(删除phone)：', my_dict)   # KeyError: 'phone'
        print('---------del删除结束！---------------')
        my_dict_1 = {'name': 'cendy', 'age': 18, 'sex': '女', 'address': '上海'}
        print('my_dict_1：', my_dict_1)
        delete_address_value = my_dict_1.pop('address')
        print(f'删除的address的值为：{delete_address_value}')
        print('my_dict_1(删除address)：', my_dict_1)
    except Exception as e:
        print('程序执行出错，抛出异常：', e)
# 删除最后一个键值对，并将删除的键值对返回
def dict_delete_popitem():
    try:
        my_dict = {'name': 'cendy', 'age': 18, 'sex': '女', 'address': '上海'}
        print('my_dict：', my_dict)
        delete_tuple = my_dict.popitem()
        print(f'删除的键值对为：{delete_tuple}')
        print('-------------popitem()-删除最后一个键值对，不传参------------------------')
        my_dict_1 = {'name': 'cendy', 'age': 18, 'sex': '女', 'address': '上海'}
        print('my_dict_1：', my_dict_1)
        delete_tuple1 = my_dict.popitem('age')  # dict.popitem() takes no arguments (1 given)
        print(f'删除的键值对为：{delete_tuple1}')
    except  Exception as e:
        print('程序执行出错，抛出异常：', e)


if __name__ == '__main__':
    dict_add()
    # dict_update()
    # dict_delete()
    # dict_delete_popitem()
